"""
S4API Unified Logging System
Author: S4MUEL
GitHub: https://github.com/S4MUEL-404/ComfyUI-S4API

Consistent logging format across all S4API nodes
"""

# ANSI color codes for terminal output
class Colors:
    RED = '\033[31m'
    GREEN = '\033[32m'
    YELLOW = '\033[33m'
    BLUE = '\033[34m'
    MAGENTA = '\033[35m'
    CYAN = '\033[36m'
    WHITE = '\033[37m'
    RESET = '\033[0m'
    BOLD = '\033[1m'
    DIM = '\033[2m'

class S4APILogger:
    """Unified logging system for S4API nodes"""
    
    PREFIX = "S4API"
    
    @staticmethod
    def _format_message(level: str, node: str, message: str) -> str:
        """Format log message with consistent style"""
        if level == "ERROR":
            icon = "❌"
            color = Colors.RED
        elif level == "WARNING": 
            icon = "⚠️"
            color = Colors.YELLOW
        elif level == "SUCCESS":
            icon = "✅"
            color = Colors.GREEN
        elif level == "INFO":
            icon = "ℹ️"
            color = Colors.CYAN
        elif level == "DEBUG":
            icon = "🔧"
            color = Colors.DIM
        elif level == "PROCESS":
            icon = "🔄"
            color = Colors.BLUE
        elif level == "ANALYZE":
            icon = "🔍"
            color = Colors.MAGENTA
        elif level == "GENERATE":
            icon = "🚀"
            color = Colors.GREEN
        elif level == "CACHE":
            icon = "💾"
            color = Colors.CYAN
        else:
            icon = "📝"
            color = Colors.WHITE
        
        return f"{color}{Colors.BOLD}[{S4APILogger.PREFIX}]{Colors.RESET} {icon} {color}{node}:{Colors.RESET} {message}"
    
    @staticmethod
    def error(node: str, message: str):
        """Log error message"""
        print(S4APILogger._format_message("ERROR", node, message))
    
    @staticmethod
    def warning(node: str, message: str):
        """Log warning message"""  
        print(S4APILogger._format_message("WARNING", node, message))
    
    @staticmethod
    def success(node: str, message: str):
        """Log success message"""
        print(S4APILogger._format_message("SUCCESS", node, message))
    
    @staticmethod
    def info(node: str, message: str):
        """Log info message"""
        print(S4APILogger._format_message("INFO", node, message))
    
    @staticmethod
    def debug(node: str, message: str):
        """Log debug message"""
        print(S4APILogger._format_message("DEBUG", node, message))
    
    @staticmethod
    def process(node: str, message: str):
        """Log processing message"""
        print(S4APILogger._format_message("PROCESS", node, message))
    
    @staticmethod
    def analyze(node: str, message: str):
        """Log analysis message"""
        print(S4APILogger._format_message("ANALYZE", node, message))
    
    @staticmethod
    def generate(node: str, message: str):
        """Log generation message"""
        print(S4APILogger._format_message("GENERATE", node, message))
    
    @staticmethod
    def cache(node: str, message: str):
        """Log cache message"""
        print(S4APILogger._format_message("CACHE", node, message))

# Convenience function for common logging patterns
def log_api_start(node: str, api_name: str, params: dict = None):
    """Log API call start"""
    param_str = ""
    if params:
        param_items = []
        for k, v in params.items():
            if isinstance(v, str) and len(v) > 50:
                param_items.append(f"{k}: {v[:50]}...")
            else:
                param_items.append(f"{k}: {v}")
        param_str = f" ({', '.join(param_items)})"
    
    S4APILogger.analyze(node, f"Starting {api_name} API call{param_str}")

def log_api_success(node: str, api_name: str, result_info: str = ""):
    """Log API call success"""
    info_str = f" - {result_info}" if result_info else ""
    S4APILogger.success(node, f"{api_name} API call completed{info_str}")

def log_cache_hit(node: str, cache_key: str):
    """Log cache hit"""
    S4APILogger.cache(node, f"Cache hit - using cached result for key: {cache_key[:16]}...")

def log_cache_miss(node: str, cache_key: str):
    """Log cache miss"""
    S4APILogger.cache(node, f"Cache miss - generating new result for key: {cache_key[:16]}...")

def log_processing_step(node: str, step: str, details: str = ""):
    """Log processing step"""
    detail_str = f" - {details}" if details else ""
    S4APILogger.process(node, f"{step}{detail_str}")